<template>
  <div class="contenttable">
    <div class="headersearch">
      <div class="displayflex left1">
        <div class="title">项目名称：</div>
        <Select v-model="checked" :checkList1="checkList" :isTable="false" :isSearch="true" />
      </div>

      <div class="displayflex right1">
        <!-- <div class="setting666 displayflex">
          <i
            v-if="isTop"
            class="el-icon-refrigerator"
            @click="onSetIsTop(false)"
          />
          <i
            v-else
            class="el-icon-c-scale-to-original"
            @click="onSetIsTop(true)"
          />
        </div> -->

        <div class="datetab displayflex">
          <div :class="dataType === '天' ? 'chose' : ''" @click="choseDateType('天')">
            天
          </div>
          <div :class="dataType === '日期' ? 'chose' : ''" @click="choseDateType('日期')">
            日期
          </div>
        </div>
        <div class="datepick">
          <!-- 日期 -->
          <el-date-picker key="日期" :clearable="false" v-if="dataType === '日期'" v-model="value2" type="daterange"
            start-placeholder="开始日期" end-placeholder="结束日期" size="small" style="width: 250px" />
          <!-- 时间 -->
          <el-date-picker key="天" :clearable="false" v-else v-model="value3" type="daterange" start-placeholder="开始日期"
            end-placeholder="结束日期" size="small" style="width: 250px" />
          <!-- 时间 -->
          <div class="timer" v-if="dataType === '天'">
            <el-time-select size="small" placeholder="开始时间" v-model="startTime" style="width: 117px" :picker-options="{
              start: '00:00',
              step: '00:60',
              end: '23:00',
            }">
            </el-time-select>
            <div>
              -
            </div>
            <el-time-select size="small" placeholder="结束时间" v-model="endTime" style="width: 117px" :picker-options="{
              start: '00:00',
              step: '00:60',
              end: '24:00',
              minTime: startTime,
            }" :disabled="!this.startTime">
            </el-time-select>
          </div>
        </div>
      </div>
    </div>

    <div class="bottomsearch1">
      <div class="">
        <Chart :checked="checked" :data="handleChildrenData(dataAll)" />
      </div>
      <!-- <div>
        <Table :title="item" :data="handleChildrenData(dataAll, item)" />
      </div> -->
    </div>
    <div class="bottomsearch3">
      <!-- <div class="">
        <Chart :title="item" :data="handleChildrenData(dataAll, item)" />
      </div> -->
      <div>
        <Table ref="childrenRef" :checkListArr="checkList" :checked="checked" :data="handleChildrenData(dataAll)"
          :params="params" :dataType="dataType" :dataAll="dataAll" @init="init" />
      </div>
    </div>

  </div>
</template>

<script>
import Table from "./components/Table.vue";
import Chart from "./components/Chart.vue";
import Select from "./components/Select.vue";
import { projects, powerTradingData, dailySummary } from "@/api/table";
import moment from "moment";

function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    timer = setTimeout(
      () => {
        typeof fn === "function" && fn.apply(null, args);
        clearTimeout(timer);
      },
      delay > 0 ? delay : 100
    );
  };
}

function toFixed(val, fix = 3) {
  return val ? Number(val).toFixed(fix) : val;
}

export default {
  components: {
    Table,
    Chart,
    Select,
  },
  data() {
    return {
      dataType: "天",
      value2: [],
      value3: [],
      recordDate: [],
      dataRange: [],
      valueTime: [],
      startTime: "00:00",
      endTime: "24:00",
      checkList: [
        // {
        //   label: "项目一",
        //   color: "#017efa",
        // },
        // {
        //   label: "项目二",
        //   color: "#017efa",
        // },
        // {
        //   label: "项目三",
        //   color: "#017efa",
        // },
      ],
      checked: [],
      dataAll: [],
      params: {},
    };
  },

  created() {
    this.initSearch()
    this.$store.commit("setting/initSwipers");
    this.getCheckList();
  },
  watch: {
    // isTop(val) {
    //   console.log(val, "val");
    // },
    checked() {
      if (this.dataType === '天') {
        this.getPowerTradingData()
      } else if (this.dataType === '日期') {
        this.getDailySummary()
      }
    },
    dataType(val) {
      if (val === '天') {
        this.getPowerTradingData()
      } else if (val === '日期') {
        this.getDailySummary()
      }
    },
    value2(val) {
      this.onChangeDate(val)
    },
    value3(val) {
      // console.log(val, "时间变化了--------------");
      this.onChangeDateOne(val)
    },
    // valueTime(val) {
    //   console.log(val, "时间变化了--------------");
    // },
    startTime(val) {
      this.endTime = ''
      if (!val) {
        this.getPowerTradingData()
      }
    },
    endTime(val) {
      // console.log(this.startTime);
      if (this.startTime && val) {
        // this.valueTime = [this.startTime, val]
        this.getPowerTradingData()
      }
    },
  },
  mounted() { },
  computed: {
    isTop() {
      return true;
    },
  },
  methods: {
    init() {
      // console.log('1111111111111111');
      // console.log(this.$refs.childrenRef.typeObj,'typeObj999999999');

      if (this.dataType === '天') {
        this.getPowerTradingData()
      } else if (this.dataType === '日期') {
        this.getDailySummary()
      }
    },
    initSearch() {
      // this.startTime = '00:00'
      // this.endTime = '24:00'
      this.value2 = [moment().subtract(1, 'month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.value3 = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.dataType = '天'
    },
    handleData(val) {
      val.forEach((item) => {
        // item.time =
        //   item.summaryDate ||
        //   ((item.hour || item.hour === 0) && item.hour.toString() + ":00");
        item.time = (item.hour === '合计' || item.summaryDate === '合计') ? '合计' : (item.summaryDate || ((item.hour || item.hour === 0) && (item.hour.toString() + (this.recordDate[0] === this.recordDate[1] ? ':00' : ''))))
        // 中长期
        // 中长期
        item.midLongTermPower = toFixed(item.midLongTermPower, 3);
        item.midLongTermPrice = toFixed(item.midLongTermPrice, 2);
        item.midLongTermCost = toFixed(item.midLongTermCost, 2);

        // 日前
        item.dayAheadClearedPower = toFixed(item.dayAheadClearedPower, 3);
        item.dayAheadDeviationPower = toFixed(item.dayAheadDeviationPower, 3);
        item.dayAheadClearedPrice = toFixed(item.dayAheadClearedPrice, 2);
        item.dayAheadCost = toFixed(item.dayAheadCost, 2);

        // 实时
        item.realTimeClearedPower = toFixed(item.realTimeClearedPower, 3);
        item.realTimeDeviationPower = toFixed(item.realTimeDeviationPower, 3);
        item.realTimeClearedPrice = toFixed(item.realTimeClearedPrice, 2);
        item.realTimeCost = toFixed(item.realTimeCost, 2);

        // 抄表
        item.meterReadingPower = toFixed(item.meterReadingPower, 3);
        item.meterReadingAvgPrice = toFixed(item.meterReadingAvgPrice, 2);
        item.meterReadingCost = toFixed(item.meterReadingCost, 2);

        // 结算
        item.settlementPower = toFixed(item.settlementPower, 3);
        item.settlementAvgPrice = toFixed(item.settlementAvgPrice, 2);
        item.settlementCost = toFixed(item.settlementCost, 2);
      });
      return val
    },
    handleChildrenData(ll) {
      console.log(ll, 'll--------------');

      const timeArr = []
      ll.forEach(item => {
        const arr = item.dailySummaryList || item.powerTradingDataList
        item.list = this.handleData(arr)
        item.list.forEach(item1 => {
          if (item1.time && !timeArr.includes(item1.time)) {
            timeArr.push(item1.time)
          }
        })
      })

      // console.log(ll, timeArr, 'll, timeArr-------------');
      const resArr = []
      timeArr.forEach(t => {
        const resObj = {
          time: t
        }

        ll.forEach(item3 => {
          const obj = item3.list.find(item2 => item2.time === t)
          if (obj) {
            Object.keys(obj).forEach(kk => {
              const val = obj[kk]
              resObj[`${item3.projectName}-${kk}`] = val
            })
          }
        })
        // console.log(resObj,'resObj---');

        resArr.push(resObj)
      })
      // console.log(resArr,'resArr--------');
      const sortedData = resArr.sort((a, b) => {
        if (moment(resArr[0].time).isValid()) {
          if (a === '合计') return 1;      // 将 '合计' 排在后面
          if (b === '合计') return -1;     // 将 '合计' 排在后面

          const dateA = moment(a, 'YYYY-MM-DD');
          const dateB = moment(b, 'YYYY-MM-DD');

          return dateA - dateB;
        }else{
          return 0
        }
        
      });
      if (resArr.length && moment(resArr[0].time).isValid()) {
        return resArr.sort((a, b) => {
          if (a.time === '合计') return 1;      // 将 '合计' 排在后面
          if (b.time === '合计') return -1;     // 将 '合计' 排在后面
          const dateA = moment(a.time, 'YYYY-MM-DD');
          const dateB = moment(b.time, 'YYYY-MM-DD');
          // return dateB - dateA
          return dateA - dateB;
      });
      }else {
        return sortedData
      }
      
    },
    async getCheckList() {
      const data = await projects()
      // const data = [
      //   {
      //     projectId: "1", // 项目id
      //     companyId: "1", // 所属公司
      //     projectName: "周覃", //项目名称
      //   },
      // ];
      this.checkList = data.map((item) => {
        return {
          ...item,
          label: item.projectName,
          color: "#017efa",
        };
      });
      this.checked = [this.checkList[0].label];
    },
    // 按天维度获取用电数据
    async getPowerTradingData() {
      const projectIds = this.checkList.filter(item => this.checked.includes(item.label)).map(item => item.projectId).toString()
      if (projectIds) {
        const params = { ...this.$refs.childrenRef.typeObj, projectIds, recordDate: this.recordDate[0], endRecordDate: this.recordDate[1], }
        if (this.startTime && this.endTime) {
          params.startHour = Number.parseInt(this.startTime)
          params.endHour = Number.parseInt(this.endTime)
        } else {
          params.startHour = 0
          params.endHour = 24
        }
        this.params = params
        const res = await powerTradingData(params)
        if (res && res.length) {
          this.dataAll = res || []
        } else {
          this.dataAll = []
        }
      } else {
        this.params = null
        this.dataAll = []
      }

    },
    // 日期
    async getDailySummary() {
      const projectIds = this.checkList.filter(item => this.checked.includes(item.label)).map(item => item.projectId).toString()
      if (projectIds) {
        const params = { ...this.$refs.childrenRef.typeObj, projectIds, startDate: this.dataRange[0], endDate: this.dataRange[1] }
        this.params = params
        const res = await dailySummary(params)
        this.dataAll = res || []
      } else {
        this.params = null
        this.dataAll = []
      }

    },
    choseDateType(val) {
      this.dataType = val;
    },
    onChangeDate(val) {
      const start = moment(val[0]).format("YYYY-MM-DD");
      const end = moment(val[1]).format("YYYY-MM-DD");
      this.dataRange = [start, end]
      this.getDailySummary()
    },
    onChangeDateOne(val) {
      if (val && val.length === 2) {
        const date1 = moment(val[0]).format("YYYY-MM-DD");
        const date2 = moment(val[1]).format("YYYY-MM-DD");
        this.recordDate = [date1, date2]
      } else {
        this.recordDate = [null, null]
      }

      this.getPowerTradingData()
    },
    onChangeTime(val) {
      console.log(val, "onChangeTime---------");
    },
    onSetIsTop(val) {
      this.$store.commit("setting/updateSwiper", { val, type: "isTop" });
    },
  },
};
</script>
<style lang="scss" scoped>
.contenttable {
  background-color: #05096a;
  width: 100%;
  height: 100%;
  min-width: 1000px;
  overflow: auto;

  .title {
    text-wrap: nowrap;
  }

  .left1 {
    // width: calc(100% - 436px);
  }

  .right1 {
    // width: fit-content;
    // width: 436px;
    justify-content: end;
    overflow: hidden;

    .setting666 {
      margin-right: 8px;
      cursor: pointer;

      >i {
        font-size: 24px;
        color: #1082fa;
      }
    }
  }

  .headersearch {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    height: 50px;
    width: calc(100% - 49px);
    background: #04065f;
    box-shadow: inset 0px 0px 34px 0px rgba(17, 40, 255, 0.66);
    border: 2px solid #0D53B7;
    border-radius: 4px;
    margin: 12px;

    .displayflex {
      display: flex;
      align-items: center;
    }

    .datepick {
      display: flex;
      align-items: center;
      margin-left: 8px;

      .timer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-left: 12px;
        width: 250px;

        :nth-child(2) {
          margin: 0 4px;
        }
      }
    }

    .datetab {
      background: #04065f;
      width: 150px;
      height: 32px;
      border-radius: 4px;
      padding: 4px;
      font-size: 16px;
      color: #a8acb2;
      border: 1px solid #66FFFF;

      >div {
        width: 70px;
        text-align: center;
        cursor: pointer;
      }

      .chose {
        background: #017efa;
        height: 28px;
        line-height: 28px;
        border-radius: 4px;
        color: #FFFFFF;
        box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .bottomsearch1 {
    // height: calc(50% - 42px);
    height: 340px;

    // border-radius: 4px;
    // height: calc(100% - 84px);
    >div {
      padding: 12px;
      background: #04065f;
      box-shadow: inset 0px 0px 34px 0px rgba(17, 40, 255, 0.66);
      border: 2px solid #0D53B7;
      height: 100%;
      // height: calc(100% - 24px);
      // height: calc(50% - 24px);
      width: calc(100% - 48px);
      margin: 12px;
      border-radius: 4px;
      padding-bottom: 0;
      box-sizing: border-box;
    }
  }

  .bottomsearch3 {

    // height: 530px;
    // overflow: hidden;
    // height: fit-content;
    // background: red;
    // border-radius: 4px;
    // height: calc(100% - 410px);
    >div {
      padding: 12px;
      background: #04065f;
      box-shadow: inset 0px 0px 34px 0px rgba(17, 40, 255, 0.66);
      border: 2px solid #0D53B7;
      height: 100%;
      // height: calc(100% - 24px);
      // height: calc(50% - 24px);
      width: calc(100% - 48px);
      margin: 12px;
      border-radius: 4px;
      // padding-bottom: 0;
      box-sizing: border-box;
    }
  }

  .bottomsearch2 {
    height: 400px;
    display: flex;
    justify-content: space-between;

    >div {
      padding: 12px;
      background: #ffffff;
      // height: calc(50% - 24px);
      width: 48%;
      // width: calc(100% - 24px);
      margin: 12px;
      border-radius: 4px;
      padding-bottom: 0;
    }
  }

  // >div{
  //     padding: 12px;
  //     width: 50%;
  // }
}
</style>
